package com.zhuoyue.web.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhuoyue.biz.core.api.dao.DeviceDao;
import com.zhuoyue.biz.core.api.domain.DeviceDO;
import com.zhuoyue.biz.core.api.dto.rep.JointControlRelationRepDTO;
import com.zhuoyue.biz.core.api.dto.req.JointControlRelationDTO;
import com.zhuoyue.biz.core.api.service.GatewayRedisService;
import com.zhuoyue.common.aop.auth.CheckLogin;
import com.zhuoyue.common.aop.auth.User;
import com.zhuoyue.common.exception.ErrorType;
import com.zhuoyue.common.exception.ZyServerException;
import com.zhuoyue.common.utils.Time;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.zhuoyue.biz.core.api.domain.JointControlRelationDO;
import com.zhuoyue.biz.core.api.service.JointControlRelationService;
import com.zhuoyue.common.dto.BatchResultDTO;
import com.zhuoyue.common.dto.ControllerResult;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wjming
 * @ClassName: AppJointControlRelationController
 * @Description:联控绑定配置
 * @Date 2021/2/14 19:58
 */
@RestController
@Scope("prototype")
@RequestMapping("/api/jointControlRelation")
@Validated
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AppJointControlRelationController {

    private final JointControlRelationService jointControlRelationService;
    private final DeviceDao deviceDao;
    private final GatewayRedisService gatewayRedisService;

    /**
     * 清空指令
     */
    private final String clerCmd = "0201${gatewayMac}${zigbeeMac}17732103FFFFFFFFFFFFFFFFFFFFFFFF";

    /**
     * 查询设备联控绑定信息
     *
     * @param startDeviceMac
     * @param startDeviceNum 04_1
     * @return
     */
    @GetMapping("/get")
    @CheckLogin
    public ControllerResult getJointControlRelationList4010(String startDeviceMac, String startDeviceNum, String gateWayId, HttpServletRequest request) {
        User user = (User) request.getAttribute("user");
        log.info("request -> user:[{}_{}] [relationList_4010] -> [startDeviceMac:{},startDeviceNum:{},gateWayId:{}]", user.getAccount(), user.getOrgCode(),
                startDeviceMac, startDeviceNum, gateWayId);
        nullParamsCheck(startDeviceMac, startDeviceNum);
        BatchResultDTO<JointControlRelationDO> result = (BatchResultDTO<JointControlRelationDO>) jointControlRelationService
                .getJointControlRelationListByStartDeviceId(gateWayId, startDeviceMac, startDeviceNum, "4010");
        if (result.isFailed()) {
            return ControllerResult.toOtherFail(result.getErrorDetail(), result.getResultCode());
        }

        List<JointControlRelationDO> module = result.getModule();
        List<JointControlRelationRepDTO> dto = new ArrayList<>();

        module.stream().forEach(list -> {
            JointControlRelationRepDTO jointControlRelationRepDTO = repDTO(list);
            dto.add(jointControlRelationRepDTO);
        });
        log.info("result ->  [relationList_4010] -> [{}]", dto);
        return ControllerResult.toReturnDataSuccess("获取成功", dto);
    }


    /**
     * 查询设备联控绑定信息
     *
     * @param startDeviceMac
     * @param startDeviceNum 04_1
     * @return
     */
    @GetMapping("/get_4011")
    @CheckLogin
    public ControllerResult getJointControlRelationList4011(String startDeviceMac, String startDeviceNum, String gateWayId, HttpServletRequest request) {
        User user = (User) request.getAttribute("user");
        log.info("request -> user:[{}_{}] [relationList_4011] -> [startDeviceMac:{},startDeviceNum:{},gateWayId:{}]", user.getAccount(), user.getOrgCode(),
                startDeviceMac, startDeviceNum, gateWayId);

        nullParamsCheck(startDeviceMac, startDeviceNum);
        BatchResultDTO<JointControlRelationDO> result = (BatchResultDTO<JointControlRelationDO>) jointControlRelationService
                .getJointControlRelationListByStartDeviceId(gateWayId, startDeviceMac, startDeviceNum, "4011");
        if (result.isFailed()) {
            return ControllerResult.toOtherFail(result.getErrorDetail(), result.getResultCode());
        }
        List<JointControlRelationDO> module = result.getModule();
        List<JointControlRelationRepDTO> jointControlRelationRepDtos = new ArrayList<>();
        module.stream().forEach(list -> {
            JointControlRelationRepDTO jointControlRelationRepDTO = repDTO(list);
            jointControlRelationRepDtos.add(jointControlRelationRepDTO);
        });
        log.info("result ->  [relationList_4011] -> [{}]", jointControlRelationRepDtos);
        return ControllerResult.toReturnDataSuccess("查询设备联控绑定信息", jointControlRelationRepDtos);
    }


    /**
     * 查询设备联控绑定信息
     * 此接口现在帮4011的一路还有问题
     * 查询4030设备联控绑定信息
     */

    @GetMapping("/get_4030")
    @CheckLogin
    public ControllerResult getJointControlRelationList4030(String startDeviceMac, String gateWayId, HttpServletRequest request) {
        User user = (User) request.getAttribute("user");
        log.info("request -> user:[{}_{}] [relationList_4030] -> [startDeviceMac:{},gateWayId:{}]", user.getAccount(), user.getOrgCode(), startDeviceMac, gateWayId);

        BatchResultDTO<JointControlRelationDO> result = (BatchResultDTO<JointControlRelationDO>) jointControlRelationService
                .getJointControlRelationListByStartDeviceId(gateWayId, startDeviceMac, "", "4030");
        if (result.isFailed()) {
            return ControllerResult.toOtherFail(result.getErrorDetail(), result.getErrorDetail());
        }
        List<JointControlRelationDO> module = result.getModule();
        List<JointControlRelationRepDTO> jointControlRelationRepDtos = new ArrayList<>();
        module.stream().forEach(list -> {
            JointControlRelationRepDTO jointControlRelationRepDTO = repDTO(list);
            jointControlRelationRepDtos.add(jointControlRelationRepDTO);
        });
        return ControllerResult.toReturnDataSuccess("查询成功", jointControlRelationRepDtos);
    }


    /**
     * 新增设备联控绑定信息
     *
     * @param jointControlRelationDTO
     * @return
     */
    @PostMapping("/add")
    @CheckLogin
    public ControllerResult addJointControlRelation(@RequestBody JointControlRelationDTO jointControlRelationDTO, HttpServletRequest request) {
        User user = (User) request.getAttribute("user");
        log.info("request -> user:[{}_{}] [addJointControlRelation] -> [startDeviceMac:{},gateWayId:{}]", user.getAccount(), user.getOrgCode(),
                JSONObject.toJSONString(jointControlRelationDTO));
        JointControlRelationDO relation = new JointControlRelationDO();
        relation.setGateWayId(jointControlRelationDTO.getGateWayId());
        relation.setStartDeviceId(jointControlRelationDTO.getStartDeviceId());
        relation.setEndDeviceId(jointControlRelationDTO.getEndDeviceId());
        relation.setStartDeviceMac(jointControlRelationDTO.getStartDeviceMac());
        relation.setEndDeviceMac(jointControlRelationDTO.getEndDeviceMac());
        relation.setStartDeviceNum(jointControlRelationDTO.getStartDeviceNum());
        relation.setEndDeviceNum(jointControlRelationDTO.getEndDeviceNum());
        JointControlRelationDO jointControlRelationDO = jointControlRelationService.addJointControlRelation(relation, jointControlRelationDTO.getOdIndex());
        JointControlRelationRepDTO jointControlRelationRepDTO = repDTO(jointControlRelationDO);
        log.info("result ->  [addJointControlRelation] -> [{}]", jointControlRelationDTO);
        return ControllerResult.toReturnDataSuccess("添加成功", jointControlRelationRepDTO);
    }

    /**
     * 当前联控信息删除只是单路删除
     *
     * @param id
     * @param startDeviceMac
     * @param request
     * @return
     */
    @DeleteMapping("/delete")
    @CheckLogin
    public ControllerResult deleteJointControlRelation(@NotBlank(message = "id不能为空") String id,
                                                       @NotBlank(message = "MAC地址不能为空") String startDeviceMac,
                                                       HttpServletRequest request) {
        User user = (User) request.getAttribute("user");
        log.info("request -> user:[{}_{}] [deleteJointControlRelation] -> [id:{},startDeviceMac:{}]", user.getAccount(), user.getOrgCode(), id, startDeviceMac);
        boolean removeById = jointControlRelationService.removeById(id);
        if (!removeById) {
            throw new ZyServerException(ErrorType.OBJECT_NOT_FOUND.getCode(), "删除失败");
        }
        List<DeviceDO> deviceDos = deviceDao.selectList(Wrappers.<DeviceDO>lambdaQuery()
                .eq(DeviceDO::getZigbeeMac, startDeviceMac));
        if (CollectionUtils.isEmpty(deviceDos)) {
            return ControllerResult.toParamFail("此设备已被删除");
        }
        int count = jointControlRelationService.count(Wrappers.<JointControlRelationDO>lambdaQuery()
                .eq(JointControlRelationDO::getStartDeviceMac, startDeviceMac)
                .eq(JointControlRelationDO::getGateWayId, deviceDos.get(0).getGatewayId()));
        log.info("result ->  [deleteJointControlRelation] -> [relationCount:{}]", count);
        return ControllerResult.toReturnDataSuccess("删除成功", count);
    }

    /**
     * 一键清空
     *
     * @param startDeviceMac
     * @return
     */
    @DeleteMapping("/clear/relation")
    @CheckLogin
    public ControllerResult clearJointControlRelation(@NotBlank(message = "MAC地址不能为空") String startDeviceMac,
                                                      HttpServletRequest request) {
        User user = (User) request.getAttribute("user");
        log.info("request -> user:[{}_{}] [clearJointControlRelation] -> [startDeviceMac:{}]", user.getAccount(), user.getOrgCode(), startDeviceMac);
        DeviceDO deviceDO = deviceDao.selectByMac(startDeviceMac);
        if (deviceDO == null) {
            throw new ZyServerException(ErrorType.result_not_exist);
        }
        jointControlRelationService.remove(Wrappers.<JointControlRelationDO>lambdaQuery()
                .eq(JointControlRelationDO::getStartDeviceMac, startDeviceMac));

        Map map = new HashMap(5);
        map.put("gatewayMac", deviceDO.getGatewayMac());
        map.put("zigbeeMac", startDeviceMac);
        //发送清空命令
        String clear = new StrSubstitutor(map).replace(clerCmd);
        gatewayRedisService.writeDataToGateway(deviceDO.getGatewayMac(), clear);
        return ControllerResult.toReturnMessageSuccess("清空命令发送成功");
    }


    private JointControlRelationRepDTO repDTO(JointControlRelationDO jointControlRelationDO) {
        JointControlRelationRepDTO jointControlRelationRepDTO = new JointControlRelationRepDTO();
        BeanUtils.copyProperties(jointControlRelationDO, jointControlRelationRepDTO);
        jointControlRelationRepDTO.setCreateTime(Time.toLongMilli(jointControlRelationDO.getCreateTime()));
        return jointControlRelationRepDTO;
    }

    private void nullParamsCheck(String startDeviceMac, String startDeviceNum) {
        if (StringUtils.isEmpty(startDeviceMac) || StringUtils.isEmpty(startDeviceNum)) {
            throw new ZyServerException(ErrorType.OBJECT_NOT_FOUND.getCode(), "设备信息不能为空");
        }
    }

    public static void main(String[] args) {
        String text = "0201{1}{1}17732103FFFFFFFFFFFFFFFFFFFFFFFF";
        String format = MessageFormat.format(text, "AAA", "GGG");
        System.out.println("format = " + format);
    }

}
